package com.qs.javame.thread1028.demo;

import java.util.LinkedList;
import java.util.List;

/**
 * 分析：
 * 3个窗口卖20张票，首先3个窗口是固定的，可以理解为3个线程；
 * 20张票为公共资源，3个窗口同时卖票，票编号不能重复。
 */
public class TestDemo {

    public static void main(String[] args) {

        //获取所有的20张票（公共资源）
        LinkedList<Ticket> ticketList = getTickets();

        for (int i = 0; i < 5; i++) {
            new Thread(new Station(ticketList)).start();
        }

    }

    private static LinkedList<Ticket> getTickets() {
        LinkedList<Ticket> ticketList = new LinkedList<>();
        for (int i = 2000; i >= 1; i--) {
            ticketList.add(new Ticket(String.valueOf(i), "张三" + i));
        }

        return ticketList;
    }
}


class Station implements Runnable {

    private LinkedList<Ticket> ticketList;

    public Station(LinkedList<Ticket> ticketList) {
        this.ticketList = ticketList;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                int size = ticketList.size();
                if (size == 0) {
                    System.out.println(Thread.currentThread().getName() + "-票卖完了。。");
                    break;
                }

                Ticket ticket = ticketList.poll();
                System.out.println(Thread.currentThread().getName() + "-卖出：" + ticket);
            }
        }
    }
}


class Ticket {

    private String ticketNo;

    private String ticketName;

    public Ticket() {

    }

    public Ticket(String ticketNo, String ticketName) {
        this.ticketNo = ticketNo;
        this.ticketName = ticketName;
    }

    public String getTicketNo() {
        return ticketNo;
    }

    public void setTicketNo(String ticketNo) {
        this.ticketNo = ticketNo;
    }

    public String getTicketName() {
        return ticketName;
    }

    public void setTicketName(String ticketName) {
        this.ticketName = ticketName;
    }

    @Override
    public String toString() {
        return "Ticket{" +
                "ticketNo='" + ticketNo + '\'' +
                ", ticketName='" + ticketName + '\'' +
                '}';
    }
}